/*
 * @Author: 千锋爱佛僧
 * @公众号: 大前端私房菜
 * @Slogan: 千锋精品教程，好学得不像实力派！
 */
/*
 * @Author: 千锋爱佛僧
 * @公众号: 大前端私房菜
 * @Slogan: 千锋精品教程，好学得不像实力派！
 */
import React, { Key, useEffect, useState } from "react";
import { Button, Drawer, Image, Space, Table, Tag, Popconfirm } from "antd";
import type { ColumnsType } from "antd/es/table";
import { categoryGet } from "@/api/pro";
import { useNavigate } from "react-router-dom";
import qs from "query-string";
import { RoleType } from "@/types/user";
import RoleForm from "./components/role-form";
import { roleBatchDel, roleDel, roleGet } from "@/api/user";
import { breadMap } from "@/utils/tool";

// const data: RoleType[] = [
//   {
//     objectId: "sss",
//     roleName: "管理员",
//     checkedKeys: [],
//   },
// ];

const RoleManager: React.FC = () => {
  let [data, setData] = useState<RoleType[]>([]);
  let [open, setOpen] = useState<boolean>(false);
  let breadMapList = breadMap(); //获取path跟菜单名称的映射数据
  let [recordData, setRecordData] = useState<RoleType | null>(null);
  let [roleIdx, setRoleIdx] = useState<number>(-1);
  // let [selectedRowKeys, setRowKeys] = useState<Key[]>([]);
  let [selectedRows, setRows] = useState<Array<RoleType>>([]);
  const navigate = useNavigate();
  const columns: ColumnsType<RoleType> = [
    {
      title: "角色名称",
      dataIndex: "roleName",
      key: "roleName",
      width: 100,
    },
    {
      title: "角色权限",
      dataIndex: "checkedKeys",
      key: "checkedKeys",
      render: (keys) => {
        return keys.map((item: string) => {
          return (
            <Tag color="geekblue" key={item}>
              {breadMapList[item]}
            </Tag>
          );
        });
      },
    },
    {
      title: "操作",
      key: "action",
      render: (_, record, index) => (
        <Space size="middle">
          <Button
            type="primary"
            size="small"
            onClick={() => {
              setOpen(true);
              setRecordData(record);
              setRoleIdx(index);
            }}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定删除吗？"
            description="删除后数据无法找回?"
            onConfirm={() => {
              handleConfirm(record, index);
            }}
            okText="确认"
            cancelText="取消"
          >
            <Button type="primary" size="small" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];
  const handleClose = () => {
    setOpen(false);
  };
  // 实时更新角色列表
  const handleRoleList = (role: RoleType, index: number) => {
    console.log(index);
    if (index == -1) {
      data.push(role);
    } else {
      data[index] = role;
    }
    setData([...data]);
    setOpen(false);
  };
  const handleConfirm = (record: RoleType, idx: number) => {
    console.log("确定删除");
    roleDel(record.objectId).then((res) => {
      data.splice(idx, 1);
      setData([...data]);
    });
  };
  useEffect(() => {
    roleGet().then((res) => {
      let result = res.data.results.map((item: RoleType, idx: number) => {
        return {
          ...item,
          idx,
        };
      });
      setData(result);
    });
  }, []);

  // 表格勾选
  const rowSelection = {
    onChange: (selectedRowKeys: Key[], selectedRows: RoleType[]) => {
      console.log(
        `selectedRowKeys: ${selectedRowKeys}`,
        "selectedRows: ",
        selectedRows
      );
      // setRowKeys(selectedRowKeys);
      setRows(selectedRows);
    },
  };
  //批量删除
  const handleBatchDel = () => {
    roleBatchDel(selectedRows).then((res) => {
      let arr: RoleType[] = data;
      selectedRows.forEach((item) => {
        arr = arr.filter((itm) => item.objectId != itm.objectId);
      });
      setData([...arr]);
    });
  };
  return (
    <>
      <Space>
        <Button
          type="primary"
          onClick={() => {
            setOpen(true);
            setRecordData(null);
            setRoleIdx(-1);
          }}
        >
          新增角色
        </Button>
        {selectedRows.length ? (
          <Button type="primary" danger onClick={handleBatchDel}>
            批量删除
          </Button>
        ) : (
          ""
        )}
      </Space>
      <Table
        columns={columns}
        dataSource={data}
        rowSelection={rowSelection}
        rowKey="objectId"
      />
      ;
      <Drawer
        title="新增角色"
        open={open}
        onClose={handleClose}
        placement="right"
      >
        <RoleForm
          initData={recordData}
          handleRoleList={handleRoleList}
          idx={roleIdx}
        />
      </Drawer>
    </>
  );
};

export default RoleManager;
